﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using ScreenRecorderLib;
using Path = System.IO.Path;
using WindowsDisplayAPI;
using System.Diagnostics;
using Tesseract;

namespace SmartOCR
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Recorder _rec;
        private DispatcherTimer _progressTimer;
        private int _secondsElapsed;
        private bool _isRecording;
        private System.Windows.Rect cropRect;

        private TesseractEngine tesseract;
        private string parsedText = "";

        public bool IsRecording
        {
            get { return _isRecording; }
            set
            {
                _isRecording = value;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        private void _progressTimer_Tick(object sender, EventArgs e)
        {
            _secondsElapsed++;
        }

        private void Rec_OnRecordingFailed(object sender, RecordingFailedEventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
            {
                IsRecording = false;
            }));
        }
        private void Rec_OnRecordingComplete(object sender, RecordingCompleteEventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
            {
                string filePath = e.FilePath;
                IsRecording = false;
                Debug.WriteLine("Rec_OnRecordingComplete=" + filePath);

                tesseract = new TesseractEngine("tessdata", "chi_sim", EngineMode.Default);

                var pix = Pix.LoadFromFile(filePath);
                var page = tesseract.Process(pix);
                parsedText += page.GetText();

                parseResult.Text = parsedText;
                parseState.Content = "提取文本";
            }));
        }

        private void _rec_OnSnapshotSaved(object sender, SnapshotSavedEventArgs e)
        {
            string filepath = e.SnapshotPath;
            Debug.WriteLine("_rec_OnSnapshotSaved=" + filepath);
        }

        private void _rec_OnStatusChanged(object sender, RecordingStatusEventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
            {

            }));
        }

        private void parseText(object sender, RoutedEventArgs e)
        {
            if (IsRecording)
            {
                _rec.Stop();
                _progressTimer?.Stop();
                _progressTimer = null;
                _secondsElapsed = 0;
                return;
            }

            parseState.Content = "提取中...";

            string videoPath = Path.Combine(Path.GetTempPath(), "SmartOCR", DateTime.Now.Millisecond + ".jpg");
            _progressTimer = new DispatcherTimer();
            _progressTimer.Tick += _progressTimer_Tick;
            _progressTimer.Interval = TimeSpan.FromSeconds(1);
            _progressTimer.Start();

            int right;
            int bottom;
            int left;
            int top;

            if (cropRect.Width == 0 || cropRect.Height == 0)
            {
                left = 0;
                top = 0;
                right = (int) SystemParameters.PrimaryScreenWidth;
                bottom = (int) SystemParameters.PrimaryScreenHeight;
            } else {
                left = (int)cropRect.Left;
                top = (int)cropRect.Top;
                right = (int)cropRect.Right;
                bottom = (int)cropRect.Bottom;
            }
            Debug.WriteLine("main cropRect: left=" + left + ",top=" + top + ",right=" + right + ",bottom=" + bottom);

            Display selectedDisplay = Display.GetDisplays().ToList()[0];

            RecorderOptions options = new RecorderOptions
            {
                RecorderMode = RecorderMode.Snapshot,
                RecorderApi = RecorderApi.DesktopDuplication,
                IsThrottlingDisabled = false,
                IsHardwareEncodingEnabled = false,
                IsLowLatencyEnabled = false,
                IsMp4FastStartEnabled = false,
                IsFragmentedMp4Enabled = false,
                IsLogEnabled = true,
                LogSeverityLevel = LogLevel.Debug,

                AudioOptions = new AudioOptions
                {
                    IsAudioEnabled = false,
                },
                VideoOptions = new VideoOptions
                {
                    BitrateMode = BitrateControlMode.Quality,
                    Quality = 70,
                    SnapshotFormat = ScreenRecorderLib.ImageFormat.JPEG,
                    SnapshotsWithVideo = false,
                },
                DisplayOptions = new DisplayOptions
                {
                    MonitorDeviceName = selectedDisplay.DisplayName,
                    Left = left,
                    Top = top,
                    Right = right,
                    Bottom = bottom
                }
            };

            if (_rec == null)
            {
                _rec = Recorder.CreateRecorder(options);
                _rec.OnRecordingComplete += Rec_OnRecordingComplete;
                _rec.OnRecordingFailed += Rec_OnRecordingFailed;
                _rec.OnStatusChanged += _rec_OnStatusChanged;
                _rec.OnSnapshotSaved += _rec_OnSnapshotSaved;
            }
            else
            {
                _rec.SetOptions(options);
            }
            _rec.Record(videoPath);
            _secondsElapsed = 0;
            IsRecording = true;
        }

        public void setCropRect(System.Windows.Rect rect)
        {
            cropRect = rect;
        }

        private void drawCropArea(object sender, RoutedEventArgs e)
        {
            //Application.Current.MainWindow.Hide();
            MaskWindow maskWindow = new MaskWindow();
            maskWindow.setCropRect = setCropRect;
            maskWindow.ShowDialog();
        }

        private void clearResult(object sender, RoutedEventArgs e)
        {
            parsedText = "";
            parseResult.Text = "";
        }
    }
}
